const router = require('koa-router')();
const { query } = require("../mysql/query.js"); //引入异步查询方法
const { SHOW_ALL_DB, QUERY_DATAS } = require("../mysql/sql.js"); //部分引入sql库

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

router.get('/getpage', async (ctx, next) => {
  let query_res = await query(
    "SELECT * FROM page"
  )
  ctx.body = query_res
})

router.get('/getpagedetail/:pageid', async (ctx, next) => {
  console.log(ctx.params.pageid)
  let res1 = await query(
    "SELECT * from reply where targetPageId = " + ctx.params.pageid
  )
  let res2 = await query(
    "SELECT * from reply2 where targetPageId = " + ctx.params.pageid
  )
  for (let z = 0; z < res1.length; z++) {
    res1[z].reply2 = []
  }

  for (let i = 0; i < res2.length; i++) {
    for (let j = 0; j < res1.length; j++) {
      if (res1[j].replyId == res2[i].targetReplyId) {
        res1[j].reply2.push(res2[i])
        break;
      }
    }
  }
  ctx.body = res1
})

module.exports = router
